//
//  PacketDispathCenter.m
//  HiQ
//
//  Created by 庞孟羽 on 12-7-30.
//
//

#import "PacketDispathCenter.h"
#import "MainWindowController.h"
#import "BuddyListPacketProcess.h"
#import "ListenPortPacketProcess.h"
#import "ClusterChatSource.h"
#import "AddNewFriendCenter.h"

//static NSMutableArray *pairChatArray = nil;
////static NSMutableArray *groupChatArray = nil;
//static NSMutableArray *clusterChatArray = nil;

@implementation PacketDispathCenter

//@synthesize delegate;

//+ (NSMutableArray *) pairChatArray
//{
//    if (pairChatArray == nil) {
//        pairChatArray = [[NSMutableArray alloc] initWithCapacity:1];
//    }
//    return pairChatArray;
//}
//
//+ (NSMutableArray *) groupChatArray
//{
//    if (groupChatArray == nil) {
//        groupChatArray = [[NSMutableArray alloc] initWithCapacity:1];
//   }
//    return groupChatArray;
//}
//
//+ (NSMutableArray *) clusterChatArray
//{
//    if(clusterChatArray == nil){
//        clusterChatArray = [[NSMutableArray alloc] initWithCapacity:1];
//    }
//    return clusterChatArray;
//}

-(id) init
{
    connection = [Connection sharedServerConnection];
    connection.delegate = self;
    return self;
}

- (void) dispathPacket:(NSData *)data
{
    //    NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    //    NSLog(@"dispathPacket  recv:%@",msg);
    
    UTF8Char * bytes = (UTF8Char *)[data bytes];
    NSUInteger fun =*((NSUInteger *)bytes);
    
    NSString *msg = [[NSString alloc] initWithBytes:(bytes+16)
                                             length:(data.length-16) encoding:NSUTF8StringEncoding];
    
    NSUInteger subFun = *((NSUInteger*)(bytes+8));
    
    //解包出窗口类型
    switch (fun) {
        case CMD_FUN_LOG:
        {
            [[LoginServer sharedLoginServer] onReceiveLoginPacket:data];
        }
            break;
        case CMD_FUN_REGISTER:
        {
            [[RegisterUser sharedLoginServer] onReceiveRegisterPacket:data];
        }
            break;
        case CMD_FUN_GROUP:
        {
            if(subFun == CMD_GROUP_CREATE_YES )
            {
                [[NewDiscussionSource shareNewDiscussion] onReceiveNewDiscussionPacket:data];
                return;
            }
            
            if(subFun == CMD_GROUP_LIST_REPLY)
            {
                [[[MainWindowController sharedMainWindowController] clusterListPacketCenter] onReceiveClusterListPacket:data];
                return;
            }
            
            if (subFun == CMD_GROUP_EXIT_REPLY) {
                [[[MainWindowController sharedMainWindowController] exitDiscussion] onReceiveExitDiscussion:data];
                return;
            }
            
            if (subFun == CMD_GROUP_MEMBERLIST_REPLY) 
            {
                NSUInteger groupID = *((NSUInteger*)(bytes+16));            
                [NSApp requestUserAttention:NSInformationalRequest];
                
//                for (ClusterChatWindowController *pc in [[MainWindowController sharedMainWindowController] clusterChatArray]) 
//                {
//                    if (groupID == [[[pc clusterChatSource] _cluster] clusterId] ) 
//                    {
//                        [[pc clusterChatSource] onReceiveClusterMemberPacket:data];
//                    }
//                }
                NSMutableArray *clusterChatArray = [[MainWindowController sharedMainWindowController] clusterChatArray];
                for(NSUInteger i = 0; i < [clusterChatArray count] ; ++i)
                {
                    ClusterChatWindowController *pc = [clusterChatArray objectAtIndex:i];
                    if (groupID == [[[pc clusterChatSource] _cluster] clusterId] ) 
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[pc clusterChatSource] onReceiveClusterMemberPacket:data];
                        });
                    }
                    
                }
                
            }
        }
            break;
        case CMD_FUN_GROUPCHAT:
        {
            NSArray *msgArray = [msg componentsSeparatedByString:@"/"];
            NSUInteger groupId = [[msgArray objectAtIndex:0] integerValue];
            NSString *groupName = [msgArray objectAtIndex:1];
            NSString *userName = [msgArray objectAtIndex:3];
            NSString *chatMsg = [msgArray objectAtIndex:4];
            
            
            //dock图标跳动
            [NSApp requestUserAttention:NSInformationalRequest];
            
            bool flag = YES;
            for (ClusterChatWindowController *pc in [[MainWindowController sharedMainWindowController] clusterChatArray]) {
                if (groupId == [[[pc clusterChatSource] _cluster] clusterId]) 
                {
                    if ([pc isShow] == YES) 
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[pc clusterChatSource] onreceiveChatMsg:chatMsg Name:userName];
                            [pc.window makeKeyAndOrderFront:self];
                        });
                    }
                    else 
                    {
                        [SCNotificationUtils notifyClusterChatWithTitle:groupName description:chatMsg GroupId:groupId]; 
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[pc clusterChatSource] onreceiveChatMsg:chatMsg Name:userName];
                        });                        
                    }
                    flag = NO;
                    break;
                }
            }
            //如果没有打开此联系人的窗口，则创建一个growl提示
            if (flag) {
                //创建窗口，但是不显示
                [[MainWindowController sharedMainWindowController] prepareClusterWindowForGrowl:groupId chatMessage:chatMsg];
                [SCNotificationUtils notifyClusterChatWithTitle:groupName description:chatMsg GroupId:groupId];                
                
                for (ClusterChatWindowController *pc in [[MainWindowController sharedMainWindowController] clusterChatArray]) {
                    if (groupId == [[[pc clusterChatSource] _cluster] clusterId]) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[pc clusterChatSource] onreceiveChatMsg:chatMsg Name:userName];
                        });
                        break;
                    }
                }
            }
        }
            break;
        case CMD_FUN_CHAT:
        {
            //解包出对方qq
            NSArray *msgArray = [msg componentsSeparatedByString:@"/"];
            NSUInteger perrQQ = (NSUInteger)[[msgArray objectAtIndex:1] intValue];
            NSString *chatMsg = [msgArray objectAtIndex:2];
            
            //dock图标跳动
            [NSApp requestUserAttention:NSInformationalRequest];
            
            bool flag = YES;
            for (PairChatWindowController *pc in [[MainWindowController sharedMainWindowController] pairChatArray]) {
                if (perrQQ == [[pc peerBuddy] buddyQQ]) 
                {
                    if ([pc isShow] == YES) 
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[pc pairChat] packetHandler:chatMsg];
                            [pc.window makeKeyAndOrderFront:self];
                        });
                    }
                    else 
                    {
                        [SCNotificationUtils notifyPairChatWithTitle:[msgArray objectAtIndex:1] description:chatMsg peerId:perrQQ];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[pc pairChat] packetHandler:chatMsg]; 
                        });    
                    }
                    flag = NO;
                    break;
                }
            }
            //如果没有打开此联系人的窗口，则创建一个growl提示
            if (flag) {
                //创建窗口，但是不显示
                [[MainWindowController sharedMainWindowController] prepareWindowForGrowl:perrQQ chatMessage:chatMsg];
                [SCNotificationUtils notifyPairChatWithTitle:[msgArray objectAtIndex:1] description:chatMsg peerId:perrQQ];
                
                for (PairChatWindowController *pc in [[MainWindowController sharedMainWindowController] pairChatArray]) {
                    if (perrQQ == [[pc peerBuddy] buddyQQ]) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[pc pairChat] packetHandler:chatMsg];   
                        }); 
                        break;
                    }
                }
            }
        }
            break;
        case CMD_FUN_BUDDYLIST:
        {
            BuddyListPacketProcess *buddyListPacketProcess = [[MainWindowController sharedMainWindowController] buddyListPacketProcess];
            [buddyListPacketProcess onReceiveBuddyListPacket:data];
            break;
        }
        case CMD_FUN_STATUSNOTIFY:
        {
            BuddyStatusPacketProcess *buddyStatusPacketProcess = [[MainWindowController sharedMainWindowController] buddyStatusPacketProcess];
            [buddyStatusPacketProcess onReceiveBuddyStatusNotify:data];
            break;
        }
        case CMD_FUN_LISTENPORT:
        {
            ListenPortPacketProcess *listenPortPacketProcess = [[MainWindowController sharedMainWindowController] listenPortPacketProcess];
            [listenPortPacketProcess onReceiveListPortPacket:data];
            break;
        }
        case CMD_FUN_HEART_BEAT:
        {
            HeartBeatPacketProcess *heartBeatPacketProcess = [[MainWindowController sharedMainWindowController] heartBeatPacketProcess];
            [heartBeatPacketProcess onReceiveHeartBeatPacket:data];
            break;
        }
        case CMD_FUN_ADD_NEW_FRIEND:
        {
            AddNewFriendCenter *addNewFriendCenter = [[MainWindowController sharedMainWindowController] addNewFriendCenter];
            [addNewFriendCenter onReceiveAddNewFriendReply:data];
            break;
        }
            
        default:
            break;
    }
}

@end
